
var treeOption = {};
var _parentNode;
var _childNodesFromServer;
var enable = true;
var curStatus = "init", curAsyncCount = 0, asyncForAll = false, goAsync = false;
var setting = null;
//增加节点
function addNode(nodeName, nodeId, parentId, isTop,) {
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    var newNode = {name: nodeName, id: nodeId, parentId: parentId};
    if (!isTop) {
        parentNode = _parentNode = treeObj.getNodeByParam('id',parentId);
    } else {
        parentNode = null;
    }
    newNode = treeObj.addNodes(parentNode, newNode, false);
}

//修改节点
function updateNode(treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    treeObj.updateNode(treeNode);
}

//删除节点
function removeNode(treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    treeObj.removeNode(treeNode);
}

function beforeAsync() {
    curAsyncCount++;
}

function onAsyncSuccess(event, treeId, treeNode, msg) {
    curAsyncCount--;
    if (curStatus == "expand") {
        expandNodes(treeNode.children);
    } else if (curStatus == "async") {
        asyncNodes(treeNode.children);
    }

    if (curAsyncCount <= 0) {
        if (curStatus != "init" && curStatus != "") {
            asyncForAll = true;
        }
        curStatus = "";
    }
    _loadingClose();
}

function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
    curAsyncCount--;

    if (curAsyncCount <= 0) {
        curStatus = "";
        if (treeNode!=null) asyncForAll = true;
    }
}

function zTreeBeforeClick () {

}

function expandAll() {
    if (!check()) {
        return;
    }
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    if (asyncForAll) {
        zTree.expandAll(true);
    } else {
        expandNodes(zTree.getNodes());
        if (!goAsync) {
            curStatus = "";
        }
    }
}

function expandNodes(nodes) {
    if (!nodes) return;
    curStatus = "expand";
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    for (var i = 0, l = nodes.length; i < l; i++) {
        zTree.expandNode(nodes[i], true, false, false);
        if (nodes[i].isParent && nodes[i].zAsync) {
            expandNodes(nodes[i].children);
        } else {
            goAsync = true;
        }
    }
}

function reset() {
    if (!check()) {
        return;
    }
    asyncForAll = false;
    goAsync = false;
    $.fn.zTree.init($("#treeDemo"), setting);
}
function check() {
    if (curAsyncCount > 0) {
        return false;
    }
    return true;
}

function initSetting() {
    setting = {
        async: {
            enable: true,
            url: Url.creatUrl(treeOption.treeList, {}),
            autoParam: ["id"],
            dataFilter: function(treeId, parentNode, childNodes){
                if (!childNodes) return null;
                _childNodesFromServer = childNodes;
                return _childNodesFromServer;
            }
        },
        edit: {
            enable: enable,
            showRenameBtn: false,
            drag: {
                isCopy: false,
                isMove: false
            }
        },
        callback: {
            beforeRemove: function(treeId, treeNode){
                remove(treeNode);
                return false;
            },
            beforeAsync: beforeAsync,
            onAsyncSuccess: onAsyncSuccess,
            onAsyncError: onAsyncError,
            beforeClick: zTreeBeforeClick
        },
        view: {
            addDiyDom: function(treeId, treeNode) {
                var aObj = $("#" + treeNode.tId + "_a");
                if ($("#diyBtn_" + treeNode.id).length > 0) return;
                var editStr = "";
                //增加
                var addChildrenUrl = Url.creatUrl(treeOption.addChildren, {id: treeNode.id});
                var addChildrenEvent = "onclick=\"locationUrl('" + addChildrenUrl + "', '增加子项')\"";
                editStr = "<B id=\"diy_addChildren_" + treeNode.id + "\" class='tree_tool' href=\"javascript:;\" "+ addChildrenEvent +" >增加子项</B>";

                //修改
                var treeNodeJson = JSON.stringify(treeNode);
                treeNodeJson = encodeURIComponent(encodeURIComponent(treeNodeJson));
                var updateUrl = Url.creatUrl(treeOption.addChildren, {id: treeNode.id, update:1, parentId: treeNode.parentId, treeNodeJson: treeNodeJson});
                var updateEvent = "onclick=\"locationUrl('" + updateUrl+ "', '修改')\"";
                editStr += "<B id=\"diy_update_" + treeNode.id + "\" class='tree_tool' href=\"javascript:;\" "+ updateEvent +" >修改</B>";

                if (treeOption.isRole) {
                    //角色授权信息
                    var name = encodeURIComponent(encodeURIComponent(treeNode.name));
                    var roleAuthorUrl = Url.creatUrl(treeOption.authorList, {id: treeNode.id, tId: treeNode.tId, name: name});
                    var roleAuthorEvent = "onclick=\"location.href='" + roleAuthorUrl + "'\"";
                    editStr += "<B id=\"diy_roleAuthor_" + treeNode.id + "\" class='tree_tool' href=\"javascript:;\" "+ roleAuthorEvent +" >角色授权</B>";
                }

                //排序值
                var value = parseOrderValueById(treeNode.id);//根据id从服务器端返回的数据解析排序值
                var orderValueStr = "<B><input class='change_order_value' onchange='changeOrderValue(\""+ treeNode.id +"\", this)' style='width:60px; text-align:center' value='"+ value +"' /></B>";
                editStr += orderValueStr;

                //隐藏的数据ID
                var orderValueStr = "<B><input id='dataId' style='display:none' value='"+ treeNode.id +"' /></B>";
                editStr += orderValueStr;
                aObj.append(editStr);

                $("#treeDemo li").hover(function(){
                    $(this).addClass("hover")
                },function(){
                    $(this).removeClass("hover")
                })

            },
            addHoverDom: function(treeId, treeNode){
                _parentNode = treeNode;
            },
        }
    };

    if (treeOption.selectTree) {//用户添加页面
        setting.callback = {
            onClick: node_name_click,
        };
        $(function(){
            $(".layui-form-select").click(function() {
                $(".treeContent").toggle();
            });
        });
    }
    if (treeOption.justTree) {//只展示树形
        delete setting["edit"];
        delete setting["view"];
    }

    $.fn.zTree.init($("#treeDemo"), setting);
    $("#expandAllBtn").bind("click", expandAll);
    $("#resetBtn").bind("click", reset);
}

$(function () {

    if (treeOption && treeOption.treeList) {
        initSetting();
    }

    /*$(".layui-form-select").click(function() {
        $(".treeContent").toggle();
    });

    $('body').click(function(e) {
        var target = $(e.target);
        // 如果#overlay或者#btn下面还有子元素，可使用
        // !target.is('#btn *') && !target.is('#overlay *')
        if (!target.is('.treeContent *') && !target.is('.layui-form-select *') ) {
            if ( $('.treeContent').is(':visible') ) {
                $('.treeContent').hide();
            }
        }
    });*/

    // 添加按钮权限判断
    layuiReady (function() {
        setTimeout(function () {
            try {
                $("#treeDemo_1_switch")[0].click();
            } catch (e) {

            }

        }, 500);
    });
});

function addTree() {
    locationUrl(Url.creatUrl(treeOption.addChildren, {}), '添加');
}

//根据id从服务器端返回的数据解析排序值
function parseOrderValueById (id) {
    if (_childNodesFromServer != null && _childNodesFromServer.length > 0) {
        for (var i = 0; i<_childNodesFromServer.length; i++) {
            if (_childNodesFromServer[i].id == id) {
                var orderValue = _childNodesFromServer[i].orderValue;
                if (orderValue == undefined) {
                    return 0;
                } else {
                    return orderValue;
                }
            }
        }
        return 0;
    }
}

//改变排序值
function changeOrderValue(id, obj) {
    var params = {
        id: id,
        orderValue: $(obj).val(),
    };
    var data = This.jqueryAjax(treeOption.updateOrder, params);
    if (data.status == 1) {
        layerMessage(data, 1);
        $(obj).css("color", "#090");
    } else {
        layerMessage(data, 2);
    }
}

function remove(treeNode) {
    if (treeNode.isParent) {
        layer.msg("当前节点下还存在子节点，不能删除!", {icon:2});
        return;
    }
    Layui.confirm("确定删除吗", '', function(layer, index) {
        var id = treeNode.id;
        var data = This.jqueryAjax(treeOption.removeTree, {id: id});
        if (data.status == 1) {
            // 调用删除
            layerMessage(data.message, 1);
            removeNode(treeNode);
        } else {
        	layerMessage(data.message, {icon:2});
        }
    });
}

function node_name_click(event, treeId, treeNode) {
    $(".treeContent").hide();
    $("#parentName").val($("#" + treeNode.tId + "_span" ).text());
    $("#parentId").val(treeNode.id);

    try {
        privateNodeNameClick(treeNode);
    } catch (e) {

    }

    event.stopPropagation();
}